const app = getApp()
const { processListImages } = require('../../utils/image')
const request = require('../../utils/request.js');
Page({
  data: {
    currentCategory: '',
    demandList: [],
    page: 1,
    pageSize: 10,
    hasMore: true,
    loading: false,
    searchKeyword: ''
  },

  onLoad: function() {
    this.loadDemandList()
  },

  onShow: function() {
    if(app.globalData.needRefresh) {
      this.setData({
        page: 1,
        hasMore: true,
        demandList: []
      })
      this.loadDemandList()
      app.globalData.needRefresh = false;
    }
  },

  onPullDownRefresh: function () {
    this.setData({
      page: 1,
      hasMore: true,
      demandList: []
    })
    this.loadDemandList().then(() => {
      wx.stopPullDownRefresh()
    })
  },

  onReachBottom: function() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMoreDemandList()
      this.setData({ loading: true })
    }
  },

  // 加载需求列表
  loadDemandList: function() {
    return new Promise((resolve, reject) => {
      request.request({
        url: `${app.globalData.baseUrl}/api/demands`,
        method: 'GET',
        data: {
          page: this.data.page,
          pageSize: this.data.pageSize,
          type: this.data.currentCategory,
          keyword: this.data.searchKeyword
        },
        header: {
          'Authorization': `Bearer ${app.getGlobalToken()}`
        },
        success: (res) => {
          const { list, total } = res.data.data

          // 使用工具函数处理图片URL
          const processedList = processListImages(list)

          this.setData({
            demandList: [...this.data.demandList, ...processedList],
            hasMore: this.data.demandList.length + list.length < total
          })
          resolve()
        },
        fail: reject
      })
    })
  },

  // 加载更多需求列表
  loadMoreDemandList: function() {
    this.setData({
      page: this.data.page + 1
    })
    this.loadDemandList().then(() => {
      this.setData({ loading: false })
    })
  },

  // 切换分类
  switchCategory: function(e) {
    const category = e.currentTarget.dataset.category
    this.setData({
      currentCategory: category,
      page: 1,
      hasMore: true,
      demandList: []
    })
    this.loadDemandList()
  },

  // 搜索
  onSearch: function(e) {
    const keyword = e.detail.value || ''
    this.setData({
      searchKeyword: keyword,
      page: 1,
      hasMore: true,
      demandList: []
    })
    this.loadDemandList()
  },

  // 跳转到详情页
  goToDetail: function(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/demand/detail/detail?id=${id}`
    })
  },

  // 跳转到发布页
  goToPublish: function() {
    wx.navigateTo({
      url: '/pages/demand/publish/publish'
    })
  }
}) 